//
//  FMHomeViewController.m
//  PsychologyFM
//
//  Created by zhang on 16/1/11.
//  Copyright © 2016年 ZhangLuDu. All rights reserved.
//

#import "FMHomeViewController.h"
#import "PKRequestManager.h"
#import "SDCycleScrollView.h"
#import "FMRecommendModel.h"
#import "FMCategoryModel.h"
#import "FMCategoryCollectionViewCell.h"
#import "FMHotFMTableViewCell.h"
#import "FMLessonAndFMModel.h"
#import "FMNewLessonTableViewCell.h"
#import "FMDiantaiTableViewCell.h"
#import "FMDiantaiModel.h"
#import "FMCategoryViewController.h"
#import "FMDiantaiPlayViewController.h"
#import "FMFindHostViewController.h"
#import "MJRefresh.h"
@interface FMHomeViewController ()<SDCycleScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>



//  存储推荐的数据数组
@property (nonatomic,strong) NSMutableArray *recommendDataArray;
//  存储推荐的轮播图的url的数组
@property (nonatomic,strong) NSMutableArray *rotateImgsUrlArray;

//  存储category的数据数组
@property (nonatomic,strong) NSMutableArray *categoryDataArray;

//  存储热门推荐的的数据数组
@property (nonatomic,strong) NSMutableArray *hotFMDataArray;

//  存储最新心理课数据数组
@property (nonatomic,strong) NSMutableArray *newlessonDataArray;

//  存储最新fm课数据数组
@property (nonatomic,strong) NSMutableArray *newfmDataArray;

//  存储心理电台推荐数据数组
@property (nonatomic,strong) NSMutableArray *psychologyFMDataArray;

@end

@implementation FMHomeViewController



- (void)viewWillAppear:(BOOL)animated
{
//    self.navigationController = [[UINavigationController alloc]initWithRootViewController:self];
    self.navigationController.navigationBar.hidden = YES;

}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //  不允许系统为而我们自动布局
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    //  添加视图
    [self addView];
    
    [self setupProgressHUD];
    //  网络数据请求
    [self dataRequest];
  
    
    
    
}

- (void)setupProgressHUD {
    [self addAHud];
    [self show];
}

#pragma mark 进度条
- (MBProgressHUD *)addAHud {
    if (!_hud) {
        _hud = [[MBProgressHUD alloc] initWithFrame:CGRectMake(kScreenWidth / 2 - 50, kScreenHeight / 2 - 50, 100, 100)];
        _hud.minSize = CGSizeMake(100, 100);
        _hud.mode = MBProgressHUDModeIndeterminate;
//        _hud.delegate = self;
        [self.view addSubview:self.hud];
    }
    return _hud;
}

- (void)show {
    [_hud show:YES];
}
- (void)hide {
    [_hud hide:YES];
}

#pragma mark --- 添加视图
- (void)addView
{
    _homeMainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 49) style:UITableViewStyleGrouped];
    //  设置数据源和代理
    _homeMainTableView.delegate = self;
    _homeMainTableView.dataSource = self;
    //  注册cell
    
    [_homeMainTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"mycell"];
    [_homeMainTableView registerClass:[FMHotFMTableViewCell class] forCellReuseIdentifier:@"FMHotFMTableViewCell"];
    //_homeMainTableView.backgroundColor = FMRed;
    
    [_homeMainTableView registerClass:[FMNewLessonTableViewCell class] forCellReuseIdentifier:@"FMNewLessonTableViewCell"];
    
    [_homeMainTableView registerClass:[FMDiantaiTableViewCell class] forCellReuseIdentifier:@"FMDiantaiTableViewCell"];
    
    //  添加总表头
    _homeMainTableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth,kScreenWidth)];
    _homeMainTableView.tableHeaderView.backgroundColor = FMCyan;
    
    _homeMainTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 10)];
    _homeMainTableView.tableFooterView.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    [self.view addSubview:_homeMainTableView];
    

}

#pragma mark --- 网络数据请求
- (void)dataRequest
{
    [PKRequestManager requestWithUrlString:@"http://yiapi.xinli001.com/fm/home-list.json?key=c0d28ec0954084b4426223366293d190" parDic:nil method:GET finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *recommendArray = dic[@"data"][@"tuijian"];
        NSArray *categoryArray = dic[@"data"][@"category"];
        NSArray *hotFMArray = dic[@"data"][@"hotfm"];
        NSArray *newFMArray = dic[@"data"][@"newfm"];
        NSArray *newlessonArray = dic[@"data"][@"newlesson"];
        NSArray *diantaiArray = dic[@"data"][@"diantai"];
        [self hide];
        //  给数组分配空间
        _recommendDataArray = [NSMutableArray array];
        _rotateImgsUrlArray = [NSMutableArray array];
        _categoryDataArray = [NSMutableArray array];
        _hotFMDataArray = [NSMutableArray array];
        _newfmDataArray = [NSMutableArray array];
        _newlessonDataArray = [NSMutableArray array];
        _psychologyFMDataArray = [NSMutableArray array];
        //  遍历数组给对应的数据源赋值
        //  轮播图
        for (NSDictionary *smDic in recommendArray) {
            
            FMRecommendModel *model = [[FMRecommendModel alloc]init];
            [model setValuesForKeysWithDictionary:smDic];
            [_recommendDataArray addObject:model];
            
            NSString *str = smDic[@"cover"];
            [_rotateImgsUrlArray addObject:str];
            // 轮播图片比例 2:1
            // category图片比例 113:113
            
        }
        //  category
        for (NSDictionary *smDic in categoryArray) {
            FMCategoryModel *model = [[FMCategoryModel alloc]init];
            [model setValuesForKeysWithDictionary:smDic];
            [_categoryDataArray addObject:model];
            
        }
        
        // hotFM
        for (NSDictionary *smDic in hotFMArray) {
            FMLessonAndFMModel *model = [[FMLessonAndFMModel alloc]init];
            [model setValuesForKeysWithDictionary:smDic];
            [_hotFMDataArray addObject:model];
        }
        //  newlessonFM
        for (NSDictionary *smDic in newlessonArray) {
            FMLessonAndFMModel *model = [[FMLessonAndFMModel alloc]init];
            [model setValuesForKeysWithDictionary:smDic];
            [_newlessonDataArray addObject:model];
        }
        //  newFM
        for (NSDictionary *smDic in newFMArray) {
            FMLessonAndFMModel *model = [[FMLessonAndFMModel alloc]init];
            [model setValuesForKeysWithDictionary:smDic];
            [_newfmDataArray addObject:model];
        }
        //  diantai
        for (NSDictionary *smDic in diantaiArray) {
            FMDiantaiModel *model = [[FMDiantaiModel alloc]init];
            [model setValuesForKeysWithDictionary:smDic];
            [_psychologyFMDataArray addObject:model];
        }
        
        //  添加轮播图
        SDCycleScrollView *topScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth / 2) imageURLStringsGroup:_rotateImgsUrlArray];
        [_homeMainTableView.tableHeaderView addSubview:topScrollView];
        //  设置轮播图的代理
        topScrollView.delegate = self;
        
        
        //  添加category的collectionView
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        //  行列间距,内边距,滚动方向,item大小
        layout.minimumInteritemSpacing = 0;
        layout.minimumLineSpacing = 0;
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.itemSize = CGSizeMake(kScreenWidth / 4, kScreenWidth / 4);
        
        UICollectionView *categoryCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, topScrollView.bottom, kScreenWidth, kScreenWidth / 2) collectionViewLayout:layout];
        categoryCollectionView.backgroundColor = FMWhite;
        //  设置代理和数据源
        categoryCollectionView.delegate = self;
        categoryCollectionView.dataSource = self;
        //  注册cell
        [categoryCollectionView registerClass:[FMCategoryCollectionViewCell class] forCellWithReuseIdentifier:@"FMCategoryCollectionViewCell"];
        //  添加到总表头上
        [_homeMainTableView.tableHeaderView addSubview:categoryCollectionView];
        [categoryCollectionView reloadData];
        //  tableview刷新界面
        [_homeMainTableView reloadData];
        
    } error:^(NSError *error) {
        NSLog(@"%@",error);
    }];

}

#pragma mark --- tableView代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 || section == 3) {
        return 1;
    }else
    {
        return 3;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        FMHotFMTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FMHotFMTableViewCell" forIndexPath:indexPath];
        cell.modelArray = _hotFMDataArray;
        cell.homeVC = self;
        [cell.recommentCollectionView reloadData];
        return cell;
    }else if (indexPath.section == 1 || indexPath.section == 2) {
        FMNewLessonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FMNewLessonTableViewCell" forIndexPath:indexPath];
        if (indexPath.section == 1) {
            FMLessonAndFMModel *model = _newlessonDataArray[indexPath.row];
            cell.model = model;
        }else
        {
            FMLessonAndFMModel *model = _newfmDataArray[indexPath.row];
            cell.model = model;
        }
        return cell;
    }else if (indexPath.section == 3)
    {
        FMDiantaiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FMDiantaiTableViewCell" forIndexPath:indexPath];
        cell.homeVC = self;
        cell.modelArray = _psychologyFMDataArray;
        return cell;
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mycell" forIndexPath:indexPath];
    return cell;
}
//  返回分区表头的view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSArray *sectionHeaderTitleNameArray = @[@"热门推荐",@"最新心理课",@"最新FM",@"心理电台推荐"];
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
        UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 5, 40)];
    [view addSubview:leftView];
    if (section % 2 == 0) {
        leftView.backgroundColor = FMRed;
    }else
    {
        leftView.backgroundColor = FMGreen;
    }
        //view.backgroundColor = FMYellow;
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, kScreenWidth, 40)];
        label.text = sectionHeaderTitleNameArray[section];

        [view addSubview:label];
        return view;

}

//  返回分区表尾的view
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return NULL;
    }else{
    NSArray *footerNameArray = @[@"更多心理课",@"更多FM",@"更多电台"];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(15, 0, kScreenWidth - 15, 40);
    [button setTitle:footerNameArray[section - 1] forState:UIControlStateNormal];
    //button.backgroundColor = FMGreen;
    button.titleLabel.font = [UIFont systemFontOfSize:12];
    [button setTitleColor:FMGray forState:UIControlStateNormal];
    [view addSubview:button];
     //   view.backgroundColor = FMCyan;
        
//        FMDiantaiModel *model = _psychologyFMDataArray[section];
//        button.tag = [model.id intValue];
    [button addTarget:self action:@selector(footerButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        
    return view;
    }

}

- (void)footerButtonClick:(UIButton *)sender
{
    NSLog(@"%@",sender.titleLabel.text);
    if ([sender.titleLabel.text isEqualToString:@"更多心理课"]) {
        FMCategoryViewController *moreLessonClassVC = [[FMCategoryViewController alloc]init];
        NSString *urlStr = [NSString stringWithFormat:@"http://bapi.xinli001.com/fm2/broadcast_list.json/?is_teacher=1&key=c0d28ec0954084b4426223366293d190&rows=15&offset=0"];
        moreLessonClassVC.urlStr = urlStr;
        moreLessonClassVC.rootVC = _rootVC;
        moreLessonClassVC.title = @"最新心理课";
        [self stopScroll];
        [self.navigationController pushViewController:moreLessonClassVC animated:YES];
    }
    if ([sender.titleLabel.text isEqualToString:@"更多FM"]) {
        FMCategoryViewController *moreLessonClassVC = [[FMCategoryViewController alloc]init];
        NSString *urlStr = [NSString stringWithFormat:@"http://bapi.xinli001.com/fm2/broadcast_list.json/?is_teacher=0&key=c0d28ec0954084b4426223366293d190&rows=15&offset=0"];
//        moreLessonClassVC.category_id
        moreLessonClassVC.urlStr = urlStr;
        moreLessonClassVC.rootVC = _rootVC;
        moreLessonClassVC.title = @"最新电台";
        [self stopScroll];
        [self.navigationController pushViewController:moreLessonClassVC animated:YES];
    }
    if ([sender.titleLabel.text isEqualToString:@"更多电台"]) {
        FMFindHostViewController *findHostVC = [[FMFindHostViewController alloc]init];
        findHostVC.title = @"发现主播";
        findHostVC.rootVC = _rootVC;
        
        NSString *urlStr = [NSString stringWithFormat:@"http://yiapi.xinli001.com/fm/diantai-page.json?key=c0d28ec0954084b4426223366293d190"];
        findHostVC.urlStr = urlStr;
        [self stopScroll];
        [self.navigationController pushViewController:findHostVC animated:YES];
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }else
    {
        return 40;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return kScreenWidth / 3 + 60;
    }else if (indexPath.section == 1 || indexPath.section == 2) {
        return 80;
    }else
    {
        return 130;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1 || indexPath.section == 2) {
        
        FMLessonAndFMModel *model = nil;
        if (indexPath.section == 1) {
           model = _newlessonDataArray[indexPath.row];
        }else
        {
            model = _newfmDataArray[indexPath.row];
        }
        FMDiantaiPlayViewController *diantaiVC = [[FMDiantaiPlayViewController alloc]init];
        diantaiVC.rootVC = _rootVC;
        diantaiVC.value = model.id;
        [self.navigationController pushViewController:diantaiVC animated:YES];
        
        
    }
}

#pragma mark --- collectionView代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _categoryDataArray.count;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FMCategoryCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FMCategoryCollectionViewCell" forIndexPath:indexPath];
    FMCategoryModel *model = _categoryDataArray[indexPath.row];
    cell.model = model;
    cell.backgroundColor = FMWhite;
    return cell;
}

//  item选中方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    FMCategoryModel *model = _categoryDataArray[indexPath.row];
    FMCategoryViewController *categoryVC = [[FMCategoryViewController alloc]init];
    NSString *urlStr = [NSString stringWithFormat:@"http://yiapi.xinli001.com/fm/category-jiemu-list.json?key=c0d28ec0954084b4426223366293d190&category_id=%@&limit=0&offset=0",model.id];
    categoryVC.category_id = model.id;
    categoryVC.title = model.name;
    categoryVC.urlStr = urlStr;
    categoryVC.rootVC = self.rootVC;
    [self tabBarHidden];
    [self stopScroll];
    [self.navigationController pushViewController:categoryVC animated:YES];

    
}

- (void)tabBarHidden
{
    _rootVC.tabbar.hidden = YES;
}


#pragma mark --- 轮播图点击方法
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    FMDiantaiPlayViewController *diantaiVC = [[FMDiantaiPlayViewController alloc]init];
    [self stopScroll];
    FMRecommendModel *model  = _recommendDataArray[index];
    diantaiVC.value = model.value;
    diantaiVC.rootVC = _rootVC;
    [self.navigationController pushViewController:diantaiVC animated:YES];

}

#pragma mark --- 点击跳转之前,让scrollView不允许滑动
- (void)stopScroll
{
    //  跳转之前不允许scrollView滑动
//    UIScrollView *scrollview = (UIScrollView *)self.view.superview.superview.superview.superview;
    //    UIScrollView *scrollView1 = (UIScrollView *)[self.view.superview.superview.superview.superview.superview viewWithTag:100];
    UIScrollView *scrollview = _rootVC.scrollView;
    scrollview.scrollEnabled = NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
